#!/usr/bin/env python
#encoding=utf8

#参数格式: 目录 文件样式
#例如: logViewer.py /opt/logs *.log

import os,sys
import fnmatch

keywords = [] #关键字列表

#协程装饰器，避免首次调用.next
def coroutine(func):
    def start(*args, **kwargs):
        g = func(*args, **kwargs)
        g.next()
        return g
    return start

#查找病返回文件全路径
@coroutine
def findFiles(target):
	while 1:
		topdir, pattern = (yield)
		for path,dirName, fileList in os.walk(topdir):
			for name in fileList:
				if fnmatch.fnmatch(name, pattern):
					target.send(os.path.join(path, name))

#打开文件, 返回文件对象
import gzip, bz2
@coroutine
def opener(target):
	while 1:
		name = (yield)
		if name.endswith(".gz"): 
			f = gzip.open(name)
		elif name.endswith(".bz2"): 
			f = bz2.BZ2File(name)
		else: 
			f = open(name)
		target.send(f)


@coroutine
def cat(target):
	while 1:
		f = (yield)
		for line in f:
			target.send(line)

@coroutine
def grep(target):
	while 1:
		line = (yield)
		#所有的关键字都包含则显示
		if all([wd in line for wd in keywords]):
			target.send(line)

@coroutine
def printer():
	while 1:
		line = (yield)
		sys.stdout.write(line)

if __name__ == '__main__':
	if len(sys.argv) < 3:
		print '使用格式: 目录 文件样式'
		print 'logViewer.py /opt/logs *.log'
	dirName = sys.argv[1]
	pattern = sys.argv[2]

	finder = findFiles(opener(cat(grep(printer()))))
	while 1:
		words = raw_input('请输入要查找的关键字(空格隔开): ')
		if words == 'quit':
			break
		keywords = words.split(' ')
		finder.send((dirName,pattern))
